<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/27 0027
// +----------------------------------------------------------------------
// | Description:  
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\model\AttachMent;
use app\admin\service\UploadFileService;
use app\api\service\HaiDing;
use app\common\controller\AdminBaseController;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\Config;
use app\common\model\tang\Cost as CostModel;
use app\common\model\tang\CostLog;
use app\common\model\tang\CostType;
use app\common\model\tang\SubjectList;
use Jrk\Tool;
use think\facade\Db;

class Common extends AdminBaseController
{

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function getCostTypeSelect()
    {
        return  $this->fetch();
    }
    public function costPrint()
    {
        $id = $this->request->param('id');
        $model = new CostModel();
        $info = $model->with(['costType', 'merchants'])->find($id);
        if(empty($info)){
            return parent::JsonReturn("费用单不存在", 1);
        }
        if($info['start_time']){
            $info['start_time'] = date('Y-m-d',$info['start_time']);
        }
        if($info['end_time']){
            $info['end_time'] = date('Y-m-d',$info['end_time']);
        }
        $mch_info = (new Config())->find(1);
        $time = explode('-',$info['pay_time']);
        $date = explode(' ',$time[2]);
        $result['time'] = $time[0].' 年 '.$time[1].' 月 '.$date[0].' 日';
        $result['No'] = $info['bill_no'];
        $result['shoujufang'] = $info['merchants']['company'];
        $result['amount'] = $info->all_amount / 100;
        $result['liushui'] = $info['order_sn'];
        $result['zje'] = moneyToString( $result['amount']);
        $result['cost_sn'] = $info['costType']['cost_sn'];
        $result['positions_code'] = $info['merchants']['positions_code'];
        $result['brand'] = $info['merchants']['name'];
        $result['tenant_name'] = $info['merchants']['tenant_name'];
        $result['code'] = $info['merchants']['code'];
        $result['pay_user'] = $info['merchants']['tenant_name'];
        $result['title'] = $info['costType']['cost_name'].'('.$info['start_time'].'~'.$info['end_time'].')';
        $result['image'] = 'https://zdwy.kelimx.com'.$mch_info['image'];
        $result['company'] = $mch_info['receipt_company'];
        $result['fapiao_img'] = '安徽正桐实业有限公司';
        $result['pay_status'] = $info['pay_status'];
        if($info['subject_id']==3){
            $result['pay_way'] = '转账';
        }elseif($info['subject_id']==2){
            $result['pay_way'] = '余额';
        }
        else{
            $result['pay_way'] = '微信';
        }
        $result['remark'] = '该收据不作为退款依据保证金/押金退款以合同约定、实际结算的余额为准，合同到期、变更或终止后该收据作废';
        $this->assign(compact("result", "id"));
//        dump($info->toArray());
        return $this->fetch();
    }


    public function Printsum()
    {
        $id = $this->request->param("id/d");//父id
        $model = new CostModel();
        $info = $model->find($id);
        $info->print_number++;
        $res = $model->update(['print_number'=>$info->print_number],['id'=>$id]);
        if ($res) {
            return parent::JsonReturn("操作成功",0,'',['print_number'=>$info->print_number]);
        } else {
            return parent::JsonReturn("操作失败", 1);
        }
    }


    public function getCostType()
    {
        $cost_type = $this->request->param('cost_type','');
        if (empty($cost_type)){
            return self::ajaxResult($cost_type,0,1,'fail');
        }
        $cost_type = (new CostType())->where('pid','=',$cost_type)->field('id,type,name,cost_sn,tax_rate,rate')->select()->toArray();
        return self::ajaxResult($cost_type,0,0,'success');
    }
    /**
     * @return \think\response\Json
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/6/27 0027
     * @describe:
     */
    public function changeStatus()
    {
        if (IS_POST) {
            try {
                $data = $this->request->post();
                if (empty($data['table'])) {
                    return parent::JsonReturn("表名不能为空", 0);
                }
                $table = $data['table'] ? $data['table'] : "";
                $res = Db::name("{$table}")->where(["id" => (int)$data['id']])->update([$data['field'] => $data['status']]);
                if ($res !== false) {
                    return parent::JsonReturn("操作成功");
                } else {
                    return parent::JsonReturn("操作失败", 0);
                }

            } catch (\Exception $exception) {
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }
    }

    /**
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:下载 excel文件
     */
    public function download(){
        $param=$this->request->param();
        $file_name=$param['fileName'];
        $file_path=app()->getRootPath().'public/'.$param['fileName'];
        if(!file_exists($file_path)){
            $this->error("文件不存在");exit;
        }
        $file1=fopen($file_path,"r");
        Header("Content-type: application/octet-stream;charset=utf-8");
        Header("Accept-Ranges: bytes");
        header("Content-Length: " . filesize($file_path));//文件大小
        header('Content-Disposition:attachment;filename='.$file_name.'');
        ob_clean();
        flush();
        echo fread($file1,filesize($file_path)); //输出文件大小到浏览器
        fclose($file1);
        @unlink($file_path); //删除文件
        exit();
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:头像上传
     */
    public function UpImg(){
        $ok= self::UpImages("adminuser/avatar");
        if (is_array($ok)){
            return parent::JsonReturn("上传成功",1,'',$ok);
        }else{
            return parent::JsonReturn($ok,0);
        }
    }

    public function UpNoticeImg()
    {
        $ok = self::UpImages("notice/banner");
        if (is_array($ok)) {
            return parent::JsonReturn("上传成功", 1, '', $ok);
        } else {
            return parent::JsonReturn($ok, 0);
        }
    }
    /**
     * @return array|false|string|\think\response\Json
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/2 0002
     * @describe:webupload上传素材图片
     */
    public function upWebupload(){
        $res= self::UpImages("attachment/images");
        if (is_array($res)){
            return json_encode($res['dir']);
        }else{
            return $res;
        }
    }


    /**
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/2 0002
     * @describe:上传文件
     */
    public function UpFile(){
       $file= self::UpFiles("attachment/files");
        if ($file["status"]==true){
            return parent::JsonReturn("上传成功",1,'',$file);
        }else{
            return ['code' => 0, 'msg' => '上传失败'];
        }
    }


    /**
     * @return \think\response\Json
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe: 弹出层上传图片
     */
    public function UpImagesList(){
        $res= self::UpImages("attachment/images");
        if (is_array($res)){
            return parent::JsonReturn("上传成功",1,'',$res);
        }else{
            return parent::JsonReturn($res,0);
        }
    }



    /**
     * @return \think\response\Json
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:文章封面
     */
    public function UpArticlePic(){
        $res= self::UpImages("article/images");
        if (is_array($res)){
            return parent::JsonReturn("上传成功",1,'',$res);
        }else{
            return parent::JsonReturn($res,0);
        }
    }

    /**
     * @return \think\response\Json 富文本编辑
     */
    public function UpEditorPic(){
        $res= self::UpImages("editor/images");
        if (is_array($res)){
            $result['code']  =  0;  //为了照顾到layui富文本编辑器的小脾气 所以此处必须要用0表示成功
            $result['msg']   =  '上传成功';
            $result['data']['src'] = $res['dir'];
            echo json_encode($result);exit();
        }else{
            $result['code']  =  -1;  //为了照顾到layui富文本编辑器的小脾气 所以此处必须要用0表示成功
            $result['msg']   =  '上传失败';
            $result['data']['src'] = '';
            echo json_encode($result);exit();
        }
    }

    /**
     * @return array|\think\response\Json
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:Editormd 图片上传
     */
    public function uploadEditormdImages(){
        $file= self::UpImages("editormd/images",1,"editormd-image-file");
        if (is_array($file)){
            $data = ['success' => 1, 'message' => "上传成功",'url'=>$file['dir'],"time"=>time()];
            return json($data);
        }else{
            return json(['success' => 0, 'message' => $file]);
        }
    }


    /**
     * @param $path  //保存的路径
     * @param int $is_save  是否保存到数据库
     * @param string $fileName
     * @return \think\response\Json
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:公共图片上传方法
     */
    protected static function UpImages($path,$is_save=1,$fileName="file"){
        if (empty($path)) $path="common/images";
        $res= UploadFileService::instance()->setUploadPath($path)->image($fileName);
        if (is_array($res)){
             if ($is_save==1){
                 AttachMent::attachmentAdd($res['name'],$res['size'],$res['type'],$res['dir'],$res['thumb_path'],$res['image_type'],$path,$res['ext']);
             }
        }
         return $res;
    }


    /**
     * @param $path
     * @param int $is_save
     * @param string $fileName
     * @return mixed|object
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/2 0002
     * @describe:上传附件
     */
    protected static function UpFiles($path,$is_save=1,$fileName="file"){
        if (empty($path)) $path="common/files";
        $res=UploadFileService::instance()->setUploadPath($path)->file($fileName);
        $res=Tool::object_to_array($res);
        if ($res["status"]==true){
            if ($is_save==1){
                AttachMent::attachmentAdd($res['name'],$res['size'],$res['type'],$res['dir'],$res['thumb_path'],$res['image_type'],$path,$res['ext']);
            }
        }
        return $res;
    }


    /**
     * @return string
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:index
     */
    public function getCourseSelect(): string
    {
        return $this->fetch();
    }


    public function getStudentSelect(): string
    {
        return $this->fetch();
    }
    public function getStudentsSelect(): string
    {
        return $this->fetch();
    }

    public function costEdit()
    {
        $id = $this->request->param("id/d");//父id
        $info = \app\common\model\tang\Cost::with(['costRule','merchants','costType'])->find($id);
        $pay_type = (new SubjectList())->where('type','=',1)->field('id,name')->select();

        $this->assign(compact("info", "id","pay_type"));
        return $this->fetch();
    }
    public function adminEdit()
    {
        $id = $this->request->param("id/d");//父id
        $info = \app\common\model\tang\Cost::with(['costRule', 'merchants', 'costType'])->find($id)->toArray();
        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        if (!empty($info['start_time']) && !empty($info['end_time'])) {
            $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
            $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);
        }
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }

    public function adminUpdateCost()
    {
        $param = $this->request->param();
        $info = \app\common\model\tang\Cost::with(['costType'])->find($param['id']);
        if (empty($info)) {
            return self::JsonReturn('订单不存在', 0);
        }
        if (!isset($param['pay_status'])) {
            if(empty($param['refund_type'])){
                return self::JsonReturn('请选择退款去向',0);
            }
            $info->refund_type = $param['refund_type'];
            $info->pay_status = -1;
            $info->refund_reason = $param['refund_reason'];
            if ($param['refund_type'] == 2) {
                $info->save();
                return self::JsonReturn("退款成功");
            } else {
                Db::startTrans();
                try {
                    //退款至余额
                    $banlanceLog = new BalanceLog();
                    $mobile = (new \app\common\model\tang\Merchant())->where('id', $info->merchant_id)->value('mobile');
                    (new \app\common\model\tang\Merchant())->where('id', $info->merchant_id)->inc('balance', $info->pay_amount)->update();
                    $banlanceLog->edit = 1;
                    $banlanceLog->merchant_id = $info->merchant_id;
                    $banlanceLog->is_top_up = 5;
                    $banlanceLog->amount = abs($info->pay_amount);
                    $banlanceLog->mobile = $mobile;
                    $banlanceLog->remark = '退款至商户余额';
                    $banlanceLog->save();
                    $info->save();
                    Db::commit();
                    return self::JsonReturn("退款成功");
                } catch (\Exception $exception) {
                    Db::rollback();
                    return self::JsonReturn('退款失败，请重试', 0);
                }
            }
        }

        if(empty($param['pay_status'])){
            if ($info->save()) {
                return self::JsonReturn("编辑成功");
            }
        }else{
            if(!empty($info['billid'])){ //如果是海鼎侧的,则需要给海鼎推送缴费信息
                $payInfo['direction'] = 1;
                $payInfo['paymentMethod'] = 'APP';
                $payInfo['paymentOrderId'] = $info['order_sn'];
                $payInfo['dealer'] = [
                    'uuid'=>'8a0293a988c2d2120188c32b25870098',
                    'code'=>'mianbei',
                    'name'=>'米安贝',
                ];
                $payInfo['paymentDate'] = date('Y-m-d H:i:s',time());
                $payInfo['incomeDate'] = date('Y-m-d H:i:s',time());
                $payInfo['remark'] = '微信小程序收款';
                $payInfo['sourceType'] = 'cre_other';
                $payInfo['lines'] = [
                    [
                        'accId'=>$info['billid'],
                        'total'=>$info['amount']/100,
                        'paymentType'=>[
                            'uuid'=>'8a0289aa736f21880173bc84e7a36fa5',
                            'code'=>'009',
                            'name'=>'微信',
                        ],
                        'bankCode'=>'',
                        'poundage'=>''
                    ]
                ];
                $HDService = new HaiDing();
                $result = $HDService->payInfo($payInfo);
                $costLogInfo = new CostLog();
                $costLog['cost_id'] = $info['id'];
                $costLog['request_info'] = json_encode($payInfo);
                $costLog['responce_info'] = json_encode($result);
                $costLog['happen_time'] =date('Y-m-d H:i:s', time());
                $costLog['create_time'] =  time();
                $costLog['update_time'] =  time();
                $costLogInfo->save($costLog);
                if(isset($result['billNumber'])){
                    $info->return_billid = $result['billNumber'];
                }
            }
//        $info->pay_amount = abs($param['pay_amount'] * 100);
            $info->pay_amount = abs($param['pay_amount'] * 100);
            $info->amount =0;
            $info->bill_no = getBill();
//            $info->amount = abs($param['real_amount'] * 100);
            $info->remark = $param['remark'];
            $info->pay_status = $param['pay_status'] == -2 ? 0 : $param['pay_status'];
            if ($param['pay_status'] == 1) {
                $info->pay_time = date('Y-m-d H:i:s', time());  // 支付时间 审核时间
            }
        }

        if ($info->save()) {
            return self::JsonReturn("编辑成功");
        }
        return self::JsonReturn('编辑失败，请重试', 0);
    }
    /**
     *重置密码
     */
    public function resetPassword(){
        $id = $this->request->param('id');
        $type = $this->request->param('type');
        if(empty($id)||empty($type)){
            return self::JsonReturn('请传入重置密码的商户或员工',0);
        }
        if($type==1){
            (new \app\common\model\tang\Merchant())->update(['password'=>md5(123456)],['id'=>$id]);
            return parent::JsonReturn("重置成功", 1);
        }
        if($type==2){
            (new \app\common\model\tang\MerchantEmployees())->update(['password'=>md5(123456)],['id'=>$id]);
            return parent::JsonReturn("重置成功", 1);
        }
        return parent::JsonReturn("重置失败", 1);
    }
    public function UpdateCost()
    {
        $id = $this->request->param("id/d");//父id
        $pay_type = $this->request->param('pay_type');//父id
        $remark = $this->request->param('remark');//父id
        $pay_status = $this->request->param('pay_status');//父id
        $info = \app\common\model\tang\Cost::find($id);
        if (empty($info)){
            return self::JsonReturn('订单不存在',0);
        }
        if(!empty($info['billid'])){
            $payInfo['direction'] = 1;
            $payInfo['paymentMethod'] = 'APP';
            $payInfo['paymentOrderId'] = $info['order_sn'];
            $payInfo['dealer'] = [
                'uuid'=>'8a0293a988c2d2120188c32b25870098',
                'code'=>'mianbei',
                'name'=>'米安贝',
            ];
            $payInfo['paymentDate'] = date('Y-m-d H:i:s',time());
            $payInfo['incomeDate'] = date('Y-m-d H:i:s',time());
            $payInfo['remark'] = '微信小程序收款';
            $payInfo['sourceType'] = 'cre_other';
            $payInfo['lines'] = [
                [
                    'accId'=>$info['billid'],
                    'total'=>$info['amount']/100,
                    'paymentType'=>[
                        'uuid'=>'8a0289aa736f21880173bc84e7a36fa5',
                        'code'=>'009',
                        'name'=>'微信',
                    ],
                    'bankCode'=>'',
                    'poundage'=>''
                ]
            ];
            $HDService = new HaiDing();
            $result = $HDService->payInfo($payInfo);
            $costLogInfo = new CostLog();
            $costLog['cost_id'] = $info['id'];
            $costLog['request_info'] = json_encode($payInfo);
            $costLog['responce_info'] = json_encode($result);
            $costLog['happen_time'] =date('Y-m-d H:i:s', time());
            $costLog['create_time'] =  time();
            $costLog['update_time'] =  time();
            $costLogInfo->save($costLog);
            if(isset($result['billNumber'])){
                $info->return_billid = $result['billNumber'];
            }
        }
        $info->subject_id = $pay_type;
        $info->remark = $remark;
        $info->pay_status = $pay_status;
        $info->pay_time = date('Y-m-d H:i:s',time());  // 支付时间 审核时间
        if ($info->save()){
            return self::JsonReturn("审核成功");
        }
        return self::JsonReturn('审核失败，请重试',0);
    }
}